//
//  MLSPictureView.swift
//  MLSMircoBlog
//
//  Created by 袁航 on 15/8/3.
//  Copyright © 2015年 yuanhang. All rights reserved.
//
import UIKit
import SDWebImage

private let pictureReuserID = "pictureReuserID"
private let itemSizeWidth: CGFloat = 90
private let itemSizeHeight: CGFloat = 90
private let flowLayoutLinSpacing: CGFloat = 5
private let flowLayoutInterSpacing: CGFloat = 5
class MLSPictureView: UICollectionView{
    // 接收数据模型
    var status: MLSUserStatus? {
        didSet {
            pictures = status?.pictURLS
        }
    }
    
    // 图片URL数组
    private var pictures: [NSURL]? {
        didSet {
            sizeToFit()
            reloadData()
        }
    }
    
    // 调用sizeToFit方法的时候,系统会默认调用下面的方法
    override func sizeThatFits(size: CGSize) -> CGSize {
        // 计算尺寸
        return calculatorSize()
    }
    // 计算尺寸
    private func calculatorSize() -> CGSize {
        
        // 定义每个cell的大小
        flowLayout.itemSize = CGSize(width: itemSizeWidth, height: itemSizeHeight)
        // 每行显示的cell的最大个数
        let rowMaxCount = 3
        flowLayout.minimumInteritemSpacing = flowLayoutLinSpacing
        flowLayout.minimumLineSpacing = flowLayoutInterSpacing
        
        // 如果没有图片
        if pictures?.count == 0 {
            return CGSizeZero
        }
        
        // 如果只有一张图片
        if pictures?.count == 1 {
            // 取出键值
            let key = pictures![0].absoluteString
            // 提取缓存image(不一定能提取出来)
            let cacheImage = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            // 设置默认的图片尺寸
            var size = CGSize(width: 160, height: 90)
            
            // 如果没有从缓存中提取到图片,就返回默认的size
            guard let image = cacheImage else {
                return size
            }
            // 提取图片的size(到这里,就一定有图片)
            size = image.size
            
            // 修改size 防止图片过大,或者过小
            size.width = (size.width < 40) ? 40 : size.width
            size.width = (size.width > UIScreen.mainScreen().bounds.width) ? 150 : size.width
            flowLayout.itemSize = size
            
            return size
        }
        
        // 如果有4张图片
        if pictures?.count == 4 {
            let w = itemSizeWidth * 2 + flowLayoutInterSpacing
            let h = itemSizeHeight * 2 + flowLayoutLinSpacing
            return CGSize(width: w, height: h)
        }
        
        // 其它情况
        /*
            2,3,5,6,7,8,9张图片
        */
        let row: CGFloat = CGFloat((pictures!.count - 1) / rowMaxCount + 1)
        let col: CGFloat = CGFloat((pictures!.count - rowMaxCount) < 0 ? pictures!.count : 3)
        if row == 1 {
            let w = CGFloat(pictures!.count) * itemSizeWidth + col * flowLayoutInterSpacing
            let h = itemSizeHeight
            return CGSize(width: w, height: h)
        } else {
            let w = col * itemSizeWidth + (col - 1) * flowLayoutInterSpacing
            let h = row * itemSizeHeight + (row - 1) * flowLayoutLinSpacing
            return CGSize(width: w, height: h)
        }
    }
    
    // 重新init方法
    // 指定布局形式
    private let flowLayout = UICollectionViewFlowLayout()
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        flowLayout.itemSize = CGSize(width: 90, height: 90)
        super.init(frame: frame, collectionViewLayout: flowLayout)
        // 背景颜色
        backgroundColor = UIColor(white: 0.98, alpha: 1)
        // 数据源代理
        dataSource = self
        // 注册可重用cell
        registerClass(MLSPictureCell.self, forCellWithReuseIdentifier: pictureReuserID)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
   
}
// 扩展类,写数据源方法
extension MLSPictureView: UICollectionViewDataSource {
    
    // MARK:- 数据源方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictures?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureReuserID, forIndexPath: indexPath) as! MLSPictureCell
        // 给cell赋模型值
        cell.pictureURL = pictures![indexPath.item]
        return cell
    }
}

class MLSPictureCell: UICollectionViewCell {
    private var pictureURL: NSURL? {
        didSet {
            imageView.sd_setImageWithURL(pictureURL)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    // 设置约束
    private func setupUI() {
        contentView.addSubview(imageView)
        // 充满contentView
        imageView.ff_Fill(contentView)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK:- cell 懒加载控件
    lazy var imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = UIViewContentMode.ScaleAspectFill;
        imageView.clipsToBounds = true
        return imageView
    }()
}